package top.kaoshanji.p1ch02a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * author kaoshanji
 * ^_^
 * create time 2024/12/23 15:04
 */
public class ConstructorUsage {

    private static final Logger logger = LogManager.getLogger(ConstructorUsage.class);

    private String outerValue;

    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {

        ConstructorUsage cu = new ConstructorUsage();

        cu.useNestedClassConstructor();
        cu.useVarargsConstructor();

    }


    public void useVarargsConstructor() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        logger.info("...代码清单 p1ch02a-02：使用反射API获取参数长度可变的构造方法(2.2.1节)...");

        Constructor<VarargsConstructor> constructor = VarargsConstructor.class.getDeclaredConstructor(String.class, String[].class);
        constructor.newInstance("", (Object) (new String[]{"A", "B", "C"}));

    }

    public void useNestedClassConstructor() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        logger.info("...代码清单 p1ch02a-03：使用反射API获取嵌套类的构造方法(2.2.1节)...");

        // 静态内部类
        Constructor<StaticNestedClass> sncc = StaticNestedClass.class.getDeclaredConstructor(String.class);
        sncc.newInstance("Alex");

        // 非静态内部类
        Constructor<NestedClass> ncc = NestedClass.class.getDeclaredConstructor(ConstructorUsage.class, int.class);
        NestedClass ic = ncc.newInstance(this, 3);
    }

    // 静态内部类
    static class StaticNestedClass {

        public StaticNestedClass(String name) {}

    }

    // 非静态内部类
    class NestedClass {

        public NestedClass(int count) {
            outerValue = "";
        }

    }



}
